package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.config.DirectConfig;
import com.bwie.mapper.TbLogMapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.param.OrderParam;
import com.bwie.pojo.TbLog;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
* @author HUAWEI
* @description 针对表【tb_order】的数据库操作Service实现
* @createDate 2025-05-19 09:50:50
*/
@Service
@Slf4j
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{
  @Autowired
  private TbOrderMapper tbOrderMapper;
  @Autowired
  private TbLogMapper tbLogMapper;
  @Autowired
  private RabbitTemplate rabbitTemplate;
  @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init(){
        //查询订单列表
        List<TbOrder> list = list();
        //存入redis缓存
        stringRedisTemplate.opsForList().rightPushAll("orderList",JSON.toJSONString(list));

    }
    @Override
    public R getOrderList(OrderParam orderParam) {
        //分页查询
        Page<TbOrder> page = new Page<>(orderParam.getPageNum(), orderParam.getPageSize());
        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
        if(orderParam.getUserId()!=null){
            wrapper.eq(TbOrder::getUserId,orderParam.getUserId());
        }
        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);
        return R.OK(tbOrderPage);
    }

    @Override
    public R updateStatus(Integer orderId) {
        //修改订单状态
        tbOrderMapper.updateStatus(orderId);
        //记录日志
        TbLog tbLog = new TbLog();
        TbUser tbUser = new TbUser();
        tbLog.setCreateTime(new Date());
        tbLog.setUserId(1);
        tbLog.setOrderStatus("已完成");
        tbLog.setUserMoney(BigDecimal.valueOf(928.00));
        tbLogMapper.insert(tbLog);

        //rabbitmq发送消息
        log.info("发送消息：");
        rabbitTemplate.convertAndSend(DirectConfig.DIRECT_EXCHANGE_ONE,
                DirectConfig.DIRECT_ROUTKING_ONE,"订单完成啦~~~");
        return R.OK();
    }

    @Override
    public R updateNum(Integer orderId) {
        //修改订单数量
        tbOrderMapper.updateNum(orderId);
        return R.OK();
    }



}




